<?php
namespace app\houtai\controller\user;
use app\houtai\controller\BaseController;
use think\Db;
use think\Request;
use think\db\Expression;
use org\GoApi\UserDetail;

class DetailController extends BaseController {
  /**
   *  @brief  : 用户详情
   *  @return : page
   *  @details: 
   */
  public function indexAction() {

    $UserID = $this->request->param('UserID/d', 0);

    $Channel = table('AccountsInfo', 'rydb.basic')->where('UserID', $UserID)->value('Channel');
    if ($Channel > 0) {
      $CHANNELS = $this->GetAdminChannel();
      if (!array_key_exists($Channel, $CHANNELS)) {
        return abort(1026, "没有权限查看[{$Channel}][{$UserID}]");
      }
    }

    $result = [];
    $pdo = table('', 'rydb.websms')->query("EXEC [dbo].[PHP_UserDetail] @dwUserID = {$UserID}", [], false, true);
    do {
      $result[] = $pdo->fetchAll(\PDO::FETCH_ASSOC);
    } while ($pdo->nextRowset());
    $eax = $result[0][0];
    if ($eax['dwResult'] != 0) {
      return abort($eax['dwResult'], $eax['szResult']);
    }
    $User = $result[1][0] ?? [];
    $Count = $result[4][0] ?? [];
    ////////////////////////////////////////////////////////////////////////////
    $listAgent = [];
    $eax = $result[3] ?? [];
    foreach($eax as $k => $v) {
      $listAgent[$v['UserID']] = $v;
    }
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'User'              => $User,
      'listCKSR'          => $result[2] ?? [],
      'listAgent'         => $listAgent,
      'listLogin'         => $result[5] ?? [],
      'listCard'          => $result[6] ?? [],
      'listPay'           => $result[7] ?? [],
      'listGame'          => $result[8] ?? [],
      'listScore'         => $result[9] ?? [],
      'listBackpack'      => $result[10] ?? [],

      'Agent'             => $result[11][0] ?? [],
      'AgentBase'         => $result[12][0] ?? [],
      'listBind'          => $result[13] ?? [],
      'listYeji'          => $result[14] ?? [],

      'UserLoginCount'    => $Count['UserLoginCount'] ?? 0,
      'RoomCardCount'     => $Count['RoomCardCount'] ?? 0,
      'RoomCardSum'       => $Count['RoomCardSum'] ?? 0,
      'ChargeOnlineCount' => $Count['ChargeOnlineCount'] ?? 0,
      'ChargeOnlineSum'   => $Count['ChargeOnlineSum'] ?? 0,
      'GameRecordCount'   => $Count['GameRecordCount'] ?? 0,
      'AgnetBindCount'    => $Count['AgnetBindCount'] ?? 0,
      'RecordDrawScoreCount'    => $Count['RecordDrawScoreCount'] ?? 0,
      'BackpackCount'    => $Count['BackpackCount'] ?? 0,

      'STATE_PAY'         => config('STATE_PAY'),
      'STATE_ORD'         => config('STATE_ORD'),
      'AGENT_TYPE'        => $User['AccountsType'] == 1 ? GetAgentType() : [],
      'LOGIN_TYPE'        => config('LOGIN_TYPE'),
      'ACCOUNTS_TYPE'     => config('ACCOUNTS_TYPE'),
      'WX_AGENT_MENUS'    => config('WX_AGENT_MENUS'),
    ]);
  }
  /**
   *  @brief  : 清零房卡
   *  @return : JSON
   *  @details: 1900
   */
  public function clearRoomCardAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $UserID = $this->request->param('uid/d', 0);
    $KindID = $this->request->param('kind/d', 0);
    $User = table('AccountsInfo', 'rydb.basic')->where('UserID', $UserID)->find();
    if (empty($User)) {
      return result([], 101, "用户UserID=[{$UserID}]不存在!");
    }
    $row = table('AccountsGameCurrency', 'rydb.basic')->where(['UserID' => $UserID])->find();
    $OldRoomCard = 0;
    if (!empty($row)) {
      $OldRoomCard = $row['RoomCard'];
      $eax = table('AccountsGameCurrency', 'rydb.basic')->where('ID', $row['ID'])->setField('RoomCard', 0);
      AddAdminLog("后台清空用户({$UserID})的房卡, 旧={$OldRoomCard}", 'Edit');
    }
    
    // 判断是否为群主
    $eax = table('Family', 'rydb.websms')->where(['AUID' => $UserID, 'State' => 1])->count();
    if ($eax > 0) {
      $eax = UserDetail::OnZengRoomCard($User['Channel'], $UserID, $KindID, $OldRoomCard, 0);
    }
    
    return result([], 0);
  }
  /**
   *  @brief  : 赠送房卡
   *  @return : JSON
   *  @details: 
   */
  public function zengRoomCardAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $UserID = $this->request->param('uid/d', 0);
    $KindID = $this->request->param('kind/d', 0);
    $zen = $this->request->param('zen/d', 0);
    if ($zen <= 0) {
      return result([], 101, '赠送金额错误!');
    }
    $OldRoomCard = 0;
    $NewRoomCard = 0;
    $User = table('AccountsInfo', 'rydb.basic')->where('UserID', $UserID)->find();
    if (empty($User)) {
      return result([], 102, "用户UserID=[{$UserID}]不存在!");
    }
    $row = table('AccountsGameCurrency', 'rydb.basic')->where(['UserID' => $UserID])->find();
    if (empty($row)) { // 无记录
      $eax = table('AccountsGameCurrency', 'rydb.basic')->insert([
        'UserID'    => $UserID,
        'RoomCard'  => $zen,
      ]);
      $OldRoomCard = 0;
      $NewRoomCard = $zen;
    } else { // 有记录
      $OldRoomCard = $row['RoomCard'];
      $NewRoomCard = $OldRoomCard + $zen;
      $eax = table('AccountsGameCurrency', 'rydb.basic')->where('ID', $row['ID'])->setInc('RoomCard', $zen);
    }
    AddAdminLog("后台赠送房卡({$zen})张给用户({$UserID})", 'Edit');
    
    
    $eax = table('CostRoomCardRecord', 'rydb.record')->insert([
      'KindID'    => $KindID,
      'dwUserID'  => $UserID,
      'dwCost'    => $zen,  // 正负数
      'dwCostType'=> 1026,
      'describe'  => "系统赠送房卡:{$zen} 剩余房卡:{$NewRoomCard}",
      'beleftRoomCard'  => $NewRoomCard,
    ]);
    
    // 判断是否为群主
    $eax = table('Family', 'rydb.websms')->where(['AUID' => $UserID, 'State' => 1])->count();
    if ($eax > 0) {
      $eax = UserDetail::OnZengRoomCard($User['Channel'], $UserID, $KindID, $OldRoomCard, $NewRoomCard);
    }
    
    return result([], 0);
  }
  /**
   *  @brief  : 赠送靓号
   *  @return : JSON
   *  @details:
   */
  public function zengGameIDAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $uid = $this->request->param('uid/d', 0);
    $newGameID = $this->request->param('nid/d', 0);
    $User = table('AccountsInfo', 'rydb.basic')->where('UserID', $uid)->find();
    if (empty($User)) {
      return result([], 101, "用户uid=[{$uid}]不存在!");
    }
    $row = table('CodeIdentifier', 'rydb.websms')->where('Code', $newGameID)->find();
    if (empty($row)) {
      return result([], 102, "靓号[{$newGameID}]不存在!");
    }
    if ($row['AccountsUsed'] > 0) {
      return result([], 103, "靓号[{$newGameID}]已被占用1!");
    }
    $eax = table('AccountsInfo', 'rydb.basic')->where('GameID', $newGameID)->count();
    if ($eax > 0) {
      return result([], 104, "靓号[{$newGameID}]已被占用2!");
    }
    if ($User['AccountsType'] != 1) {
      return result([], 105, "用户uid=[{$uid}]的账号类型不是代理, 只有代理才能分配靓号!");
    }
    table('CodeIdentifier', 'rydb.websms')->where('ID', $row['ID'])->setField('AccountsUsed', $User['UserID']);  // 标记新占用
    table('CodeIdentifier', 'rydb.websms')->where('Code', $User['GameID'])->setField('AccountsUsed', 0); // 释放旧占用
    table('AccountsInfo', 'rydb.basic')->where('UserID', $User['UserID'])->setField('GameID', $newGameID); // 更新AccountsInfo表用户GameID
    table('AgentReg', 'rydb.websms')->where('UserID', $User['UserID'])->setField('GameID', $newGameID); // 更新AgentReg表用户GameID
    
    AddAdminLog("后台赠送靓号[{$newGameID}]给用户[{$User['UserID']}],旧GameID[{$User['GameID']}]", 'Edit');
    return result([], 0);
  }
  /**
   *  @brief  : 赠送金币
   *  @return : JSON
   *  @details:
   */
  public function zengCoinAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $UserID = $this->request->param('uid/d', 0);
    $User = table('AccountsInfo', 'rydb.basic')->where('UserID', $UserID)->find();
    if (empty($User)) {
      return result([], 101, "用户uid=[{$UserID}]不存在!");
    }
    $coin = $this->request->param('coin/d', 0);
    $old = table('AccountsGameCurrency', 'rydb.basic')->where('UserID', $User['UserID'])->find();
    if (empty($old)) {
      table('AccountsGameCurrency', 'rydb.basic')->insert(['UserID' => $User['UserID']]);
      $old = table('AccountsGameCurrency', 'rydb.basic')->where('UserID', $User['UserID'])->find();
    }
    table('AccountsGameCurrency', 'rydb.basic')->where('UserID', $User['UserID'])->setInc('Gold', $coin);
    $new = table('AccountsGameCurrency', 'rydb.basic')->where('UserID', $User['UserID'])->field(['Gold','BankGold'])->find();
    
    AddAdminLog("后台赠送金币[{$coin}]给用户[{$User['UserID']}], 旧[{$old['Gold']}][{$old['BankGold']}], 新[{$new['Gold']}][{$new['BankGold']}]", 'Edit');
    
    // 记录金币帐变 
    table('RecordPresentInfo', 'rydb.record')->insert([
      'UserID'          => $User['UserID'],
      'PreScore'        => $old['Gold']*1,
      'PreInsureScore'  => $old['BankGold']*1,
      'PresentScore'    => $coin,
      'TypeID'          => 16,  // 16:后台赠送
      'IPAddress'       => $this->request->ip(),
    ]);
    return result([], 0);
  }
  /**
   *  @brief  : 清空绑定
   *  @return : JSON
   *  @details:
   */
  public function bindClearAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $UserID = $this->request->param('uid/d', 0);
    $KindID = $this->request->param('kind/d', 0);
    $User = table('AccountsInfo', 'rydb.basic')->where('UserID', $UserID)->find();
    if (empty($User)) {
      return result([], 101, "用户[{$UserID}]不存在");
    }
    $row = table('AccountsGameCurrency', 'rydb.basic')->where(['UserID' => $UserID, 'KindID' => $KindID])->find();
    if (empty($row)) {
      return result([], 102, "用户[{$UserID}][{$KindID}]绑定关系不存在, 清空绑定失败");
    }
    table('AccountsGameCurrency', 'rydb.basic')->where('ID', $row['ID'])->setField('SpreaderID', 0);
    AddAdminLog("后台清空用户[{$UserID}]的代理绑定[{$row['SpreaderID']}]", 'Edit');
    return result([], 0);
  }
  /**
   *  @brief  : 绑定代理
   *  @return : JSON
   *  @details: 
   */
  public function bindAgentAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $UserID = $this->request->param('uid/d', 0);
    $KindID = $this->request->param('kind/d', 0);
    $AGameID = $this->request->param('aid/d', 0);
    $Agent = table('AccountsInfo', 'rydb.basic')->where(['GameID' => $AGameID, 'AccountsType' => 1])->find();
    if (empty($Agent)) {
      return result([], 101, "优惠码[{$AGameID}]不存在!");
    }
    $row = table('AccountsGameCurrency', 'rydb.basic')->where(['UserID' => $UserID])->find();
    if (empty($row)) { // 无记录
      $SpreaderID = 0;
      $eax = table('AccountsGameCurrency', 'rydb.basic')->insert([
        'UserID'            => $UserID,
        'KindID'            => $KindID,
        'SpreaderID'        => $Agent['UserID'],
        'SpreaderTime'=> new Expression('GETDATE()'),
      ]);
    } else { // 有记录
      $SpreaderID = $row['SpreaderID'];
      $eax = table('AccountsGameCurrency', 'rydb.basic')->where('ID', $row['ID'])->update([
        'SpreaderID'        => $Agent['UserID'],
        'SpreaderTime'=> new Expression('GETDATE()'),
      ]);
    }
    AddAdminLog("后台给用户({$UserID})绑定代理({$AGameID}),原={$SpreaderID}", 'Edit');
    return result([], 0);
  }
  /**
   *  @brief  : 保存账号权限设置
   *  @return : JSON
   *  @details: 
   */
  public function saveRightAction(){
    $param = $this->request->param();
    $uid = $this->request->param('uid/d', 0);
    if ($uid <= 0) {
      return result([], 100, 'UID非法!');
    }

    $data = [
      'Nullity'     => $this->request->param('txtNullity/d', 0),  // 冻结帐号
      'StunDown'    => $this->request->param('txtStunDown/d', 0), // 安全关闭
      'IsAndroid'   => $this->request->param('txtIsAndroid/d', 0),// 设为机器人
      'MoorMachine' => $this->request->param('txtMoorMachine/d', 0),  // 锁定机器
      'UserRight'   => $this->request->param('txtUserRight/a', []),    // 用户权限
      'MasterOrder' => $this->request->param('txtMasterOrder/d', 0),  // 用户身份
      'MasterRight' => $this->request->param('txtMasterRight/a', []),  // 管理权限
    ];
    if ($data['Nullity'] > 0) {
      $data['NullityOverDate'] = new Expression('GETDATE()');
    } else {
      $data['NullityOverDate'] = '1900-01-01 00:00:00';
    }
    $UserRight = 0;
    foreach($data['UserRight'] as $key=>$val) {
      $eax = 1;
      $eax<<=$key;
      $UserRight |= $eax;
    }
    $data['UserRight'] = $UserRight;

    $MasterRight = 0;
    foreach($data['MasterRight'] as $key=>$val) {
      $eax = 1;
      $eax<<=$key;
      $MasterRight |= $eax;
    }
    $data['MasterRight'] = $MasterRight;
    
    table('AccountsInfo', 'rydb.basic')->where('UserID', $uid)->update($data);

    return result([], 0, '保存成功');
  }
  /**
   *  @brief  : 保存代理设置
   *  @return : JSON
   *  @details: 
   */
  public function saveAgentAction() {
    $param = $this->request->param();
    $uid = $this->request->param('uid/d', 0);
    if ($uid <= 0) {
      return result([], 100, 'UID非法!');
    }
    $data = [
      'Updatetime' => new Expression('GETDATE()'),
    ];
    ////////////////////////////
    $Agent = table('AgentReg', 'rydb.websms')->where(['UserID' => $uid])->find();
    if (empty($Agent)) {
      return result([], 101, "用户[{$uid}]不存在!");
    }
    ////////////////////////////
    $txtNavStr = $this->request->param('txtNavStr/a', [], 'trim,strtolower');
    $data['MenuStr'] = implode('_', $txtNavStr);
    ////////////////////////////
    $txtLevel = $this->request->param('txtLevel/a', [], 'intval');
    if (count($txtLevel) != 7) {
      return result([], 102, '返点比率设置有七个');
    }
    foreach($txtLevel as $k => $v) {
      if ($v >= 0 && $v <= 100) {
        $data["level{$k}"] = $v; // level0-level6
      } else {
        return result([], 103, ($k + 1).'级返点比率设置有误!0~100');
      }
    }
    ////////////////////////////
    $txtAgentLevel = $this->request->param('txtAgentLevel/d', 0);
    if ($txtAgentLevel < 0 || $txtAgentLevel > 7) {
      return result([], 104, '代理级别只有0~7级');
    }
    $data['AgentLevel'] = $txtAgentLevel;
    ////////////////////////////
    $txtParentId = $this->request->param('txtParentId/d', 0);
    if ($txtParentId < 0) {
      return result([], 105, '上级代理UserID非法');
    } else if ($txtParentId > 0) {
      $Parent = table('AgentReg', 'rydb.websms')->where(['UserID' => $txtParentId])->find();
      if (empty($Parent)) {
        return result([], 106, "上级代理UserID={$txtParentId}不存在");
      }
      $data['ParentId'] = $txtParentId;
    } else {
      $data['ParentId'] = 0;
    }
    ////////////////////////////
    $txtIsDirect = $this->request->param('txtIsDirect/b', 0);
    $txtIsDirect = $txtIsDirect ? 1 : 0;
    $data['IsDirect'] = $txtIsDirect;
    ////////////////////////////
    $txtDirectLevel = $this->request->param('txtDirectLevel/d', 0);
    if ($txtDirectLevel < 0 || $txtDirectLevel > 100) {
      return result([], 107, '直销返点百分比设置有误!0~100');
    }
    $data['DirectLevel'] = $txtDirectLevel;
    ////////////////////////////
    if (!empty($Parent) && $txtParentId > 0 && $txtAgentLevel > 0) { // 上级存在 && 当前有设置上级推广员 && 当前推广员有指定级别
      if (!$Parent['IsDirect']) { // 上级不是直销
        if ($txtAgentLevel <= $Parent['AgentLevel']) {
          return result([], 108, '当前推广员的级别不能大于上级推广员');
        }
      }
    }
    ////////////////////////////
    $DisableLogin = $this->request->param('txtDisableLogin/d', 0);
    $data['DisableLogin'] = $DisableLogin;
    ////////////////////////////
    $txtAssoFamily = $this->request->param('txtAssoFamily/s', '', 'trim');
    if (!empty($txtAssoFamily)) {
      $txtAssoFamily = explode(',', $txtAssoFamily);
      foreach($txtAssoFamily as $k => &$v) {
        $eax = preg_match_all('/(\d{6})/', $v, $matches, PREG_SET_ORDER);
        if ($eax != 1) {
          return result([], 109, '请输入有效六位群号');
        }
        $v = $matches[0][1] * 1;
      }
      $listQun = table('Family a', 'rydb.websms')->field(['a.ID', 'a.AUID', 'a.Code', 'b.Channel'])
        ->join('CYBasicDB.dbo.AccountsInfo b', 'b.UserID = a.AUID', 'LEFT')
        ->where(['a.State' => 1, 'a.Code' => ['IN', $txtAssoFamily]])
        ->select();

      foreach($txtAssoFamily as $a => $b) {
        $eax = 0;
        foreach($listQun as $c => $d) {
          if ($d['Code'] == $b) {
            $eax = 1;
            break;
          }
        }
        if ($eax == 0) {
          return result([], 110, "六位群号[{$b}]不存在");
        }
        if ($d['Channel'] != $Agent['Channel']) {
          return result([], 111, "六位群号[{$b}]的渠道号与该用户的渠道号不一致");
        }
      }
      $data['AssoFamily'] = implode(',', $txtAssoFamily);
    }

    $data['PayLv'] = $this->request->param('tetPayLv/d', 0);  // 代理后台支付面额分组

    ////////////////////////////
    $eax = table('AgentReg', 'rydb.websms')->where(['UserID'=>$uid])->update($data);
    return result([], 0, $eax ? '更新成功' : '更新失败');
  }
}
